class newPromise {
  constructor(executor) {
    this.ENUM_STATUS = {
      PADDING: '等待态',
      FULFILLED: '执行态',
      REJECTED: '失败态'
    }
    this.state = this.ENUM_STATUS.PADDING;
    this.value = ''
    // 必须存在一个被拒绝的原因
    this.reason = '';

     // 任务中心
    this.onFulfilledQueue = [];
    this.onRejectedQueue = [];
    // 转化执行态
    let resolve = (value) => {
      console.log(4)
      // 修改状态
      this.state = this.ENUM_STATUS.FULFILLED;
      // 必须有一个终值
      this.value = value;
      // 当服务器数据返回时，依次执行预存的成功事务
      this.onFulfilledQueue.map(fn => fn(this.value));
    };
    // 转化失败态
    let reject = (reason) => {
      // 修改状态
      this.state = this.ENUM_STATUS.REJECTED;
      // 如果是失败态，必须有一个据因
      this.reason = reason;
      // 当服务器数据返回时，依次执行预存的失败事务
      this.onRejectedQueue.map(fn => fn(this.reason));
    };
    // 如果executor执行报错，直接执行reject
    console.log(1)
    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err);
    }

  }

  // 必须包含then方法
  then(onFulfilled, onRejected) {
    console.log(2)
    // 保证onFulfilled和onRejected都是函数类型
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : err => {
      throw 'error'
    };
    // 如果当前状态为执行态，则执行onFulfilled函数，将终值作为该函数的参数，否则忽略其
    if (this.state === this.ENUM_STATUS.FULFILLED) {
      onFulfilled(this.value);
    }
    // 如果当前状态为拒绝态，则执行onRejected函数，将据因作为该函数的参数，否则忽略其
    if (this.state === this.ENUM_STATUS.REJECTED) {
      onRejected(this.reason);
    }
    // 如果当前状态为等待态，则将其加入事务
    if (this.state === this.ENUM_STATUS.PADDING) {
      console.log(3)
      this.onFulfilledQueue.push(() => {
        onFulfilled(this.value);
      });
      this.onRejectedQueue.push(()=> {
        onRejected(this.reason);
      });
    }

  }

}

new newPromise((resolve, reject)=>{
  setTimeout(()=>{
    resolve('成功')
    // reject('失败')
  },2000)
}).then((data) => {
  //成功回调
  console.log(data);
},(data)=>{
  //失败回调
  console.log(data)
});
